package com.cmuis.goodguide;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the homepage of the Application. This Activity creates a menu that
 * consists of all of the actions a user can do within the application. It also
 * contains the activity logo, and a brief description of the application.
 * 
 * @author Stephanie
 * 
 */
public class goodguide extends Activity {

	// all menu items
	static final String INTENT = "intentkey";
	static final String SELECTION = "selectionkey";
	static final String SEARCH = "Search";
	static final String SCAN_BARCODE = "Scan Barcode";
	static final String HISTORY = "View History";
	static final String CLEAR_QUERIES = "Clear Queries";
	static final String ABOUT_PAGE = "About the Ratings";
	// menu items to be displayed in a list format
	static final String[] selections = { SEARCH, SCAN_BARCODE, HISTORY, CLEAR_QUERIES, ABOUT_PAGE };

	/**
	 * Creates the homepage menu consisting of two buttons and a listView.
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		List<HashMap<String, Object>> displayList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> hm;

		// adds menu items
		hm = new HashMap<String, Object>();
		hm.put(SELECTION, "Search");
		hm.put(INTENT, R.drawable.icon);
		displayList.add(hm);

		hm = new HashMap<String, Object>();
		hm.put(SELECTION, "Scan Barcode");
		hm.put(INTENT, R.drawable.icon);
		displayList.add(hm);
		hm = new HashMap<String, Object>();
		hm.put(SELECTION, "View History");
		hm.put(INTENT, R.drawable.icon);
		displayList.add(hm);

		hm = new HashMap<String, Object>();
		hm.put(SELECTION, "Clear Queries");
		hm.put(INTENT, R.drawable.icon);
		displayList.add(hm);

		hm = new HashMap<String, Object>();
		hm.put(SELECTION, "About the Ratings");
		hm.put(INTENT, R.drawable.icon);
		displayList.add(hm);

		// Displays an image and text for each selection in the list
		myAdapter mSchedule = new myAdapter(goodguide.this, displayList,
				R.layout.menu_rows, new String[] { SELECTION, INTENT },
				new int[] { R.id.menu_text, R.id.menu_image });

		ListView list = (ListView) findViewById(R.id.home_view);

		list.setAdapter(mSchedule);
		// sets the actions to be done when an item is clicked in the list
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final Context activity = goodguide.this;
				if (selections[position].equalsIgnoreCase(SEARCH)) {
					ConnectivityManager cMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					boolean connected = (cMgr.getActiveNetworkInfo() != null
							&& cMgr.getActiveNetworkInfo().isAvailable() && cMgr
							.getActiveNetworkInfo().isConnected());
					// if the phone can access internet, will present the search bar
					if (connected) {
						startSearch(null, false, null, false);
						// if the phone cannot access the internet, it will present
						// an alert dialogue, and remain on the homepage
					} else {
						Log.e("error", "No connection available ");
						AlertDialog.Builder downloadDialog = new AlertDialog.Builder(
								activity);
						downloadDialog.setTitle("No Connection Found");
						downloadDialog
								.setMessage("You are not connected to any data services, please reconnect and try again");
						downloadDialog.setNeutralButton("Close",
								new DialogInterface.OnClickListener() {
									public void onClick(
											DialogInterface dialogInterface, int i) {
										return;
									}
								});
						downloadDialog.show();
					}
				}
				else if (selections[position].equalsIgnoreCase(SCAN_BARCODE)) {
					Intent i = new Intent(goodguide.this, barcodescanner.class);
					startActivity(i);
				}
				else if (selections[position].equalsIgnoreCase(HISTORY)) {
					Intent i = new Intent(goodguide.this, History.class);
					startActivity(i);
				}
				else if (selections[position].equalsIgnoreCase(ABOUT_PAGE)) {
					Intent i = new Intent(goodguide.this, InfoPage.class);
					startActivity(i);
				}
				// clears previous search queries
				else if (selections[position].equalsIgnoreCase(CLEAR_QUERIES)) {
					try {
						// creates an alert dialog so the user must confirm that
						// they do want to clear all serach queries
						new AlertDialog.Builder(goodguide.this)
								.setIcon(android.R.drawable.ic_dialog_alert)
								.setTitle(R.string.clear_query_title)
								.setMessage(R.string.clear_query)
								.setPositiveButton(
										R.string.confirm_clear_query,
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

												SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
														goodguide.this,
														ContentProvider.AUTHORITY,
														ContentProvider.MODE);

												suggestions.clearHistory();
											}
										})
								// In the case where a user decides not to clear
								// all queries
								.setNegativeButton(R.string.reject_clear_query,
										null).show();

					} catch (Exception e) {
						// do nothing
					}
				}
			}
		});

	}

	/**
	 * Creates the options ability when the menu is created.
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	/**
	 * This section details the menu items and their actions when pressed. This
	 * is the main level of navigation in the application.
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.search:
			Intent j = new Intent(this, goodguide.class);
			startActivity(j);
			return true;
		case R.id.barcode_scanner:
			Intent i = new Intent(this, barcodescanner.class);
			startActivity(i);
			return true;
		case R.id.history:
			Intent p = new Intent(this, History.class);
			startActivity(p);
			return true;
		case R.id.info:
			Intent q = new Intent(this, InfoPage.class);
			startActivity(q);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Creates a list that displays both an image and text for each item in the
	 * list. Sets the right views to be able to display unique images that
	 * correlate to each item in the list.
	 * 
	 * @author Stephanie
	 * 
	 */
	private class myAdapter extends SimpleAdapter {

		/**
		 * Maps static data views to views defined in XML. the data is defined in a ArrayList of Maps.
		 * Each entry in the ArrayList corresponds to a line in the ArrayList.
		 * 
		 * @param context
		 *            The context where the View associated with this
		 *            SimpleAdapter is running
		 * @param data
		 *            A List of Maps. Each entry in the List corresponds to one
		 *            row in the list. The Maps contain the data for each row,
		 *            and should include all the entries specified in "from"
		 * @param resource
		 *            Resource identifier of a view layout that defines the
		 *            views for this list item. The layout file should include
		 *            at least those named views defined in "to"
		 * @param from
		 *            A list of column names that will be added to the Map
		 *            associated with each item.
		 * @param to
		 *            The views that should display column in the "from"
		 *            parameter. These should all be TextViews. The first N
		 *            views in this list are given the values of the first N
		 *            columns in the from parameter.
		 */
		public myAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);

		}

		@Override
		/**
		 * Gets the view for the specific item in the list
		 * @param position The position of the item within the adapter's data set of the item whose view we want.
		 * @param convertView The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view. Heterogeneous lists can specify their number of view types, so that this View is always of the right type (see getViewTypeCount() and getItemViewType(int)).
		 * @param parent The parent that this view will eventually be attached to
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			//if a view is not specified, just use the 
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.menu_rows,
						null);
			}

			HashMap<String, Object> data = (HashMap<String, Object>) getItem(position);

			((TextView) convertView.findViewById(R.id.menu_text))
					.setText((String) data.get(SELECTION));

			ImageView image = (ImageView) convertView
					.findViewById(R.id.menu_image);
			//sets a specific image for each item in the list
			if (data.get(SELECTION) == SEARCH)
			{
				image.setImageResource(R.drawable.ic_search);
			}
			else if (data.get(SELECTION) == SCAN_BARCODE)
			{
				image.setImageResource(R.drawable.ic_barcode);
			}

			else if (data.get(SELECTION) == HISTORY) {
				image.setImageResource(R.drawable.ic_list_history);
			} 
			else if (data.get(SELECTION) == CLEAR_QUERIES)
			{
				image.setImageResource(R.drawable.ic_list_clear_query);
			}
			else if (data.get(SELECTION) == ABOUT_PAGE)
			{
				image.setImageResource(R.drawable.ic_list_about);
			}
			else
			{
				image.setImageResource(R.drawable.icon);
			}

			return convertView;
		}

	}

}